package asm.dump;

import org.ricks.common.Tuple;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author chenwei
 * @Description:
 * @date 2022/11/2415:34
 */
public class CreateDispatchJava {


    public static void createJava(List<Tuple> tuples) {
        Set<String> names = tuples.stream().map(tuple -> (String)tuple.get(1)).collect(Collectors.toSet());
        StringBuffer sb = new StringBuffer();
        sb.append("package app;\n\n");
        sb.append("import org.demon.common.Context;\n");
        sb.append("import org.demon.ioc.ApplicationContext;\n");
        for (String name: names) {
            sb.append("import " + name + ";\n");
        }
        sb.append("public class Dispatcher {\n\n");
        sb.append("  public static void dispacher(Context<Short,Byte[]> context) {\n");
        sb.append("  switch (context.getCmd()) {");
        sb.append(createSwitch(tuples));
        sb.append("    }\n");
        sb.append("  }\n");
        sb.append("}");
        File javaFile = new File("java");
        if(!javaFile.exists()) javaFile.mkdirs();
        File file1 = new File("java\\Dispatcher.java");
        FileOutputStream fop = null;
        try {
            fop = new FileOutputStream(file1);
            if (!file1.exists()) {
                file1.createNewFile();
            }
            byte[] contentInBytes = sb.toString().getBytes();

            fop.write(contentInBytes);
            fop.flush();
            fop.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Dispatcher　Done");
    }

    public static String createSwitch(List<Tuple> tuples){
        StringBuffer sb = new StringBuffer();
        sb.append("\n");
        for(Tuple tuple: tuples){
            String name = (String)tuple.get(1);
            name = name.substring(name.lastIndexOf(".") + 1,name.length());
            short cmd = tuple.get(0);
            sb.append("    case " + cmd + ":\n");
            sb.append("       ApplicationContext.getBean("+name+".class)."+tuple.get(2)+"(context);\n");
            sb.append("       break;\n");
        }
        return sb.toString();
    }

//    public static void main(String[] args) {
//        createJava();
//    }
}
